import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:手动实现一个定时器
 * User:龙宝
 * Date:2023-12-02
 * Time:20:45
 */
//先创建一个任务类
class Task implements Comparable<Task>{
    private Runnable runnable;
    private Long time;

    public Task(Runnable runnable,int time) {
        this.runnable = runnable;
        this.time = time + System.currentTimeMillis();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public Long getTime() {
        return time;
    }

    @Override
    public int compareTo(Task o) {
        long l = this.time - o.time;
        return (int)l;
    }
}
//添加，执行任务类
class RunTask {
    BlockingQueue<Task> queue = new PriorityBlockingQueue();
    private Object locker = new Object();
    //扫描类
    public RunTask()  {
        Thread t = new Thread(()-> {
            while (true) {
                try {
                    synchronized (locker) {
                        //取出首元素
                        Task task = queue.take();
                        //比较时间
                        Long time = task.getTime();
                        if(time <= System.currentTimeMillis()) {
                            //到点执行任务
                            task.getRunnable().run();
                        } else {
                            //睡眠
                            //赛会队列中
                            queue.put(task);
                            locker.wait(time - System.currentTimeMillis());
                        }
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
        t.start();

    }
    //添加任务类
    public void schedule(Runnable runnable,int time) throws InterruptedException {
        Task task = new Task(runnable,time);
        queue.put(task);
        synchronized (locker) {

            locker.notify();
        }

    }
}

public class Thread12 {
    public static void main(String[] args) throws InterruptedException {
        RunTask runTask = new RunTask();
        runTask.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("哈哈哈哈1111111111");
            }
        }, 1000);
        runTask.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("222222222222222");
            }
        }, 2000);
        runTask.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("333333333333333");
            }
        }, 500);
    }
}